from account.account_service import AccountService, accounts_write_lock
from common.logger import logger
import common.http as http
import json
import time
import spider_config


class YdtAccountService(AccountService):
    _instance = None

    def instance():
        if YdtAccountService._instance is None:
            YdtAccountService._instance = YdtAccountService()
        return YdtAccountService._instance

    def __init__(self) -> None:
        super().__init__()

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def active(self):
        self._fetch()

    def take(self):
        with accounts_write_lock:
            if len(self._accounts) > 0:
                # 对self._accounts按照used从小到大排序，结果存入sorted_accounts
                sorted_accounts = sorted(self._accounts, key=lambda x: x["used"])
                account = sorted_accounts[0]

                if account["used"] < 20:
                    account["used"] += 1
                    return account

            for i in range(10):
                self._fetch()
                if len(self._accounts) > 0:
                    return self._accounts[0]
                else:
                    logger.error("没有可用的一点停账号，等待5秒后重试")
                    time.sleep(5)

            return None

    def _fetch(self):
        params = {"token_type": 5, "second": 3000, "limit": 20, "max_used": 1, "task_id": self._task_id}
        rsp = http.get(spider_config.park_token_host + "/api/parktoken/data", params)
        data = rsp.json()["data"]
        self._clear()
        for item in data:
            account = json.loads(item["data"])
            account["used"] = 0
            self._accounts.append(account)

        logger.success(f"补充一点停账号完成，剩余账号数量: {len(self._accounts)}")
